const router = require('koa-router')()
const DB = require('../../utils/db.js')

router.post('/register', async (ctx) => {
  let data = await DB.insert('author', ctx.request.body)
  ctx.body = data
  try {
    if (data.result.ok) {
      ctx.redirect('/login/getInfo')
    }
  } catch (error) {
    ctx.redirect('/')
  }
})

router.post('/login', async (ctx) => {
  let name = ctx.request.body.name
  let email = ctx.request.body.email
  let pwd = ctx.request.body.pwd

  const result = await DB.find('author',
    { 'name': name, 'email': email, 'pwd': pwd })

  try {
    if (result.length > 0) {
      ctx.body = '登录成功'
      ctx.redirect('/')
    }
  } catch (error) {
    ctx.redirect('/')
  }
})

router.get('/getInfo', async (ctx) => {
  const result = await DB.find('author', {})
  ctx.body = result
})

module.exports = router
